import numpy as np
def roulette(population:dict):
    value_sum=sum(list(population.values()))
    sorted_data=sorted(population.items(),key=lambda x:x[1])
    p0=np.random.rand()
    p_now=0
    res=None
    # print("概率搜索-----------")
    for item in sorted_data:
        p_now+=item[1]/value_sum
        # print("样本名称{:6s}\t样本适应度{:6s}\t累计概率{:.4f}".format(item[0],str(item[1]),p_now))
        if p0<p_now:
            res=item[0]
            break
    

    # print("*"*40)
    # print("随机选择概率为 {:.4f}\t终止概率为 {:.4f}\t选择样本为 {:6s}".format(p0,p_now,res))

    
    return res


if __name__=="__main__":
    data={"1":10,"2":40,"3":20,"7":5}
    while True:
        x1=roulette(data)
        x2=roulette(data)
        if x1 != x2:
            break


    print(x1,x2)


